package com.sa.app.fragments;

import java.util.Date;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.sa.app.R;
import com.sa.app.activities.ItemActivity;

public class ItemFragment extends Fragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View v = inflater.inflate(R.layout.item, container, false);
		initializeUI(v);
		if (((ViewGroup) v.getParent()) != null) {
			((ViewGroup) v.getParent()).removeView(v);
		}
		return v;

	}

	private void initializeUI(View v) {

		ItemActivity act = (ItemActivity) getActivity();
		TextView manu = (TextView) v.findViewById(R.id.itemTitle);
		manu.setText(act.getItemActual().getManufacturer() + " "
				+ act.getItemActual().getModel());

		String NFCID = act.getItemActual().getNfcID();

		ImageView img = (ImageView) v.findViewById(R.id.imageViewMainImage);

		try {
			Drawable d = new BitmapDrawable(getActivity()
					.getApplicationContext().getFilesDir()
					+ "/"
					+ NFCID
					+ ".png");
			img.setImageDrawable(d);

		} catch (Exception e) {
			// TODO: handle exception
			img.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
		}

		// ItemLastUse
		TextView ultimaVezUtilizado = (TextView) v
				.findViewById(R.id.lastUseValue);
		Date d = act.getDataBaseManager().getItemLastUse(NFCID);
		String da = String.valueOf(DateFormat.format("dd/MM/" + d.getYear()
				+ " kk:mm", d));
		ultimaVezUtilizado.setText(da);

		// NumUses
		TextView numUses = (TextView) v.findViewById(R.id.NumUsesValue);
		Integer num = act.getDataBaseManager().getItemNumUses(NFCID);

		numUses.setText(String.valueOf(num));

		// LastRegionUse
		TextView lastRegionUse = (TextView) v
				.findViewById(R.id.itemRegionValue);
		lastRegionUse.setText(act.getDataBaseManager().getItemLastRegion(NFCID)
				.get(0));

		// RegistrationDate
		TextView registrationDate = (TextView) v
				.findViewById(R.id.registrationDateValue);
		Date date2 = act.getDataBaseManager().getItemRegistrationDate(NFCID);
		String dateStr = String.valueOf(DateFormat.format(
				"dd/MM/" + date2.getYear() + " kk:mm", date2));
		registrationDate.setText(dateStr);

	}

	// Esto hace que no cuelgue la aplicación al cambiar de activity utilizando
	// la libreria de compatibilidad
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}
}